/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》https://cxyxy.blog.csdn.net/article/details/121134634
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 **/
var app = getApp()
var interval = 0
var isStarted = false
var startTime = Date()
var lastTimeElapsed = 0
Page({
  data: {
    startPauseButtonText: '开始',
    displayTime: '00:00:000'
  },

  startOrPauseTimer() {
    if (isStarted) {
      if (interval != 0) {
        clearInterval(interval)
        interval = 0
      }
      lastTimeElapsed = new Date() - startTime + lastTimeElapsed
      this.setData({
        startPauseButtonText: '开始'
      })
    } else {
      startTime = new Date()
      this.setData({
        startPauseButtonText: '暂停'
      })

      if (interval == 0) {
        interval = setInterval(() => {
          var timeOffset = new Date() - startTime + lastTimeElapsed
          this.setData({
            displayTime: this.formatTime(timeOffset)
          })
        }, 100)
      }
    }

    isStarted = !isStarted
  },

  formatTime(timeOffset) {
    var mm = parseInt(timeOffset / 1000 / 60)
    if (mm < 10) mm = '0' + mm
    var ss = parseInt((timeOffset / 1000) % 60)
    if (ss < 10) ss = '0' + ss
    var ssss = parseInt(timeOffset % 1000)
    if (ssss < 10) {
      ssss = '00' + ssss
    } else if (ssss < 100) {
      ssss = '0' + ssss
    }
    return `${mm}:${ss}:${ssss}`
  },

  resetTimer() {
    if (interval != 0) {
      clearInterval(interval)
      interval = 0
    }
    this.setData({
      displayTime: this.formatTime(0)
    })
    isStarted = false
    lastTimeElapsed = 0
    this.setData({
      startPauseButtonText: '开始'
    })
  },
})
